package com.lagou.handler;

import com.lagou.annotation.Component;
import com.lagou.ioc.ApplicationContext;
import com.lagou.ioc.ApplicationContextAware;
import com.lagou.service.RpcRequest;
import com.lagou.service.UserService;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        RpcRequest rpcRequest = (RpcRequest) msg;
        UserService userService = (UserService) ac.getBean(rpcRequest.getClassName());
        Method[] methods = userService.getClass().getMethods();
        a:for(Method method : methods){
            if(method.getName().equals(rpcRequest.getMethodName())){
                Class<?>[] parameterTypes = method.getParameterTypes();
                for (int i = 0; i < parameterTypes.length; i++) {
                    if(parameterTypes[i] != rpcRequest.getParameterTypes()[i]){
                        break a;
                    }
                }
                //通过反射执行任务
                Object invoke = method.invoke(userService, rpcRequest.getParameters());
                System.out.println("执行完成:"+invoke);
                ctx.writeAndFlush(invoke);
                System.out.println("服务端返回执行结果");
                return;
            }
        }



    }

    private static ApplicationContext ac = null;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        ac = applicationContext;
    }
}
